package org.jash.exam.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.exam.R
import org.jash.exam.entity.ExamEntity

class ExamAdapter(private var data: List<ExamEntity>) : RecyclerView.Adapter<ExamAdapter.ExamViewHolder>() {
    class ExamViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvDate: TextView = itemView.findViewById(R.id.tvDate)
        val tvSWorkTime: TextView = itemView.findViewById(R.id.tvSWorkTime)
        val tvXWorkTime: TextView = itemView.findViewById(R.id.tvXWorkTime)
        val tvStatus: TextView = itemView.findViewById(R.id.tvStatus)
        val tvAddress: TextView = itemView.findViewById(R.id.tvAddress)



    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExamViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_exam, parent, false)
        return ExamViewHolder(view)
    }

    override fun onBindViewHolder(holder: ExamViewHolder, position: Int) {
        val item = data[position]
        val morning = item.morningCheckIn ?: ""
        val afternoon = item.afternoonCheckIn ?: ""
        if (morning.length > 15 && afternoon.length > 15) {
            holder.tvDate.text = morning.substring(0, 10)
            holder.tvSWorkTime.text = "上班:" + morning.substring(10, 16)
            holder.tvXWorkTime.text = "下班:" + afternoon.substring(10, 16)
        } else {
            holder.tvDate.text = morning
            holder.tvSWorkTime.text = "上班:" + morning
            holder.tvXWorkTime.text = "下班:" + afternoon
        }
        // 状态背景和文字
        val status = item.status
        val statusBg = when (status) {
            "正常" -> R.drawable.bg_status_normal
            "迟到" -> R.drawable.bg_status_late
            "早退" -> R.drawable.bg_status_early
            "缺勤" -> R.drawable.bg_status_absent
            else -> R.drawable.bg_status_default
        }
        holder.tvStatus.setBackgroundResource(statusBg)
        holder.tvStatus.setTextColor(Color.BLACK)
        holder.tvStatus.text = status
        holder.tvAddress.text = item.currentLocation ?: "-"
    }

    override fun getItemCount(): Int = data.size

    fun setData(newData: List<ExamEntity>) {
        data = newData
        notifyDataSetChanged()
    }
}
